var express = require('express');
var router = express.Router();
var User = require('../models/users');
var request = require('request');
var moment = require('moment');

//生成token
function createToken () {
  const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  const length = chars.length;
  let str = "";
  for (let i = 0; i < length; i++) {
    str += chars.substr(Math.round(Math.random() * length), 1);
  }
  return str;
};
//获取用户唯一ID
router.post('/', function (req, res, next) {
  var nickName = req.body.nickName;
  var avatarUrl = req.body.avatarUrl;
  var creatAt = moment().format('YYYY-MM-DD HH:mm:ss');
  var url = 'https://api.weixin.qq.com/sns/jscode2session'
  request.get({
    url: url,
    qs: {
      grant_type: 'authorization_code',
      appid: 'wxf69a98e27ab12007',
      secret: '46ad37d5888b791886eb4c9322a222c3',
      js_code: req.body.jsCode
    }
  }, (err, result, rdata) => {
    let ardata = JSON.parse(rdata);
    const { openid, session_key } = ardata
    if (result.statusCode === 200) {
      User.findOne({
        openid: openid
      }).then((userInfo) => {
        if (userInfo) {
          userInfo.openid = undefined
          res.json({
            status: '0',
            msg: '登录成功',
            data: userInfo
          })
        } else {
          var user = new User({
            openid: openid,
            nickName: nickName,
            avatarUrl: avatarUrl,
            creatAt: creatAt,
            token: createToken(),
            gropsArr: []
          })
          user.save().then((newUserInfo) => {
            if (newUserInfo) {
              newUserInfo.openid = undefined;
              res.json({
                status: '0',
                msg: '注册成功',
                data: newUserInfo
              })
            } else {
              res.json({
                status: '1',
                msg: '注册失败'
              })
            }
          });
        }
      })
    } else {
      res.json(err)
    }
  })

})
module.exports = router;